//
//  DeviceDiskVC.m
//  xychain_DM_iOS
//
//  Created by Jpwang on 2018/6/12.
//  Copyright © 2018年 Jpwang. All rights reserved.
//

#import "DeviceDiskVC.h"
#import "DeviceItem.h"
#import "DiskItemCell.h"

@interface DeviceDiskVC ()<UITableViewDelegate, UITableViewDataSource> {
    DeviceItem *mDeviceItem;
    Disks *mDisk;
}

@property(weak, nonatomic)IBOutlet UIButton *backBt;
@property(weak, nonatomic)IBOutlet UITableView *tableView;

@property(strong,nonatomic)NSMutableArray *dataSource;

@end

@implementation DeviceDiskVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setData:(DeviceItem *)deviceItem {
    mDeviceItem = deviceItem;
}

- (void)initView {
    if (!mDeviceItem) {
        [JPToast showText:@"出现了一点小故障，请稍后重试"];
        [self.navigationController popViewControllerAnimated:YES];
    }
    self.dataSource = [[NSMutableArray alloc] init];
    if (mDeviceItem.deviceState && mDeviceItem.deviceState.disks) {
        [self.dataSource addObjectsFromArray:mDeviceItem.deviceState.disks];
    }
    [[self.backBt rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"DiskItemCell" bundle:nil] forCellReuseIdentifier:@"DiskItemCellID"];
    [self.tableView reloadData];
}

- (void)requestFormat:(Disks *)disk {
    mDisk = disk;
    [self showLoading:@"正在格式化"];
    NSString *url = [NSString stringWithFormat:@"%@%@/cmd", d_cmd, mDeviceItem.sn];
    NSDictionary *dic = @{@"cmd":@"format_disk", @"content": disk.diskId};
    [[[HttpRequest shareInstance] signPost:url map:[NSMutableDictionary dictionaryWithDictionary:dic]] subscribeNext:^(id x) {
        [self hideLoading];
        if ([x[@"code"] intValue] == 200) {
            [JPToast showText:@"正在为您格式化"];
            [self checkTimer];
        } else {
            [JPToast showText:x[@"message"]];
        }
    } error:^(NSError *error) {
        [self hideLoading];
        [JPToast showText:@"网络错误"];
    }];
}

- (void)checkTimer {
    if (mDisk) {
        if (mDisk.status != 0) {
            [self performSelector:@selector(checkTimer) withObject:nil afterDelay:5];
            NSString *url = [NSString stringWithFormat:@"%@%@/state", d_detail, mDeviceItem.sn];
            [[[HttpRequest shareInstance] signGet:url map:nil] subscribeNext:^(id x) {
                if ([x[@"code"] intValue] == 200) {
                    @try {
                        if (x[@"data"]) {
                            NSDictionary *temp = x[@"data"];
                            NSDictionary *temp2 = [temp objectForKey:@"deviceState"];
                            if (temp2) {
                                NSArray *temp3 = [temp2 objectForKey:@"disks"];
                                NSArray *disks = [MTLJSONAdapter modelsOfClass:[Disks class] fromJSONArray:temp3 error:nil];
                                if (disks) {
                                    for (int i=0; i<disks.count; i++) {
                                        Disks *d = disks[i];
                                        if ([d.diskId isEqualToString:self->mDisk.diskId] && d.status && [d.status intValue] == 0) {
                                            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(checkTimer) object:nil];
                                            NSString *msg = @"格式化成功";
                                            UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
                                            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                                            [vc addAction:cancel];
                                            [self presentViewController:vc animated:YES completion:nil];
                                        }
                                    }
                                }
                            }
                        }
                    } @catch (NSException *exception) {
                        NSLog(@"error=%@",exception);
                    }
                } else {
                    [JPToast showText:x[@"message"]];
                }
            } error:^(NSError *error) {
                [JPToast showText:@"网络错误"];
            }];
        }
    }
}


#pragma mark UITableView delegate and datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DiskItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DiskItemCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setBlock:^(Disks *item) {
        NSString *msg = [NSString stringWithFormat:@"格式化硬盘将会丢失该硬盘上的所有数据，请确保该硬盘上的数据已备份，否则无法恢复。\n\n您确定要格式化“%@”吗？", item.diskId];
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self requestFormat:item];
        }];
        [vc addAction:cancel];
        [vc addAction:confirm];
        [self setUIAlertController:vc MessageAlign:NSTextAlignmentJustified];
        [self presentViewController:vc animated:YES completion:nil];
    }];
    [cell performSelector:@selector(setModel:) withObject:self.dataSource[indexPath.row]];
    return cell;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
